<script setup lang="ts">
import { onMounted } from 'vue';
import { state, filter } from './state';
import { navigateTo, getCurrentInstance, showLoading, eventCenter } from '@tarojs/taro';
import {
  Search2 as NutIconSearch2,
  HorizontalN as AppNutIconHorizontalN,
} from '@nutui/icons-vue-taro';
import { APP_PLAN_TASK_ASSET_LIST_QUERY } from '/@/api/modules/maintain/plan-task';
import {
  PLAN_TASK_STATUS,
  PLAN_TASK_STATUS_COLOR,
  PLAN_TASK_STATUS_BG_COLOR,
} from '/@/common/constant';
import planTaskHeadCard from './components/plan-task-head-card.vue';

/**
 * @description 当前路由信息
 */
const params = getCurrentInstance().router?.params as {
  id: string;
  /**
   *状态：1-已完成，2-未完成，3-待审核，4-撤销
   */
  handleStatus: string;
  /**
   * 巡检/保养类型，1-设备巡检（关联模板适用对象，1-设备），2-区域巡检（关联模板适用对象，2-区域）
   */
  planBizType: string;
  /**
   * 来源: 默认巡检 inspection/maintenance/cleaning
   */
  from?: string;
};

/**
 *
 */
const TITLE_CONSTANT = {
  maintenance: '保养任务',
  cleaning: '保洁任务',
};

/**
 *
 */
const CARD_TITLE_CONTENT = {
  maintenance: '已保养数量',
  cleaning: '已保洁数量',
};

/**
 *点击筛选图标，弹出选择窗口
 */
function displayPopup() {
  filter.filterItemVisible = !filter.filterItemVisible;
  filter.appRegionListSelectorPopupIsShow = false;
}

/**
 *筛选项选择回调
 */
function filterItemChoose(_: unknown, index: number) {
  switch (index) {
    case 0: //全部
      filter.searchRegion = '';
      refreshList();
      break;
    case 1: //区域过滤
      filter.appRegionListSelectorPopupIsShow = true;
      break;
  }
}

/**
 *@description 保养计划列表
 * @param page 当前页
 * @param pageSize -每页条数
 */
function queryList(page: number = 1, pageSize: number = 15) {
  if (!page && state.finished) return;
  state.loading = true;
  //当计划已经完成，只查询已经完成的任务列表
  if (params.handleStatus === '1') {
    state.activeStatus = 1;
  }
  showLoading();
  APP_PLAN_TASK_ASSET_LIST_QUERY({
    comQuery: { page, pageSize },
    assetName: filter.searchValue,
    planType: 1,
    planTaskId: params.id,
    handleStatus: state.activeStatus,
    areaId: filter.searchRegion,
  })
    .then((res) => {
      state.loading = false;
      if (
        state.activePage >=
        (res.comQuery?.pageCount ||
          (res.comQuery?.totalCount as number) / (res.comQuery?.pageSize as number) ||
          1)
      ) {
        state.finished = true;
        state.statusQuantity[0].title = `未巡检(${
          res.unfinishedQuantity > 99 ? '99+' : res.unfinishedQuantity
        })`;
        state.statusQuantity[1].title = `已巡检(${
          res.finishedQuantity > 99 ? '99+' : res.finishedQuantity
        })`;
      }

      if (!res.planTaskAssetDto || !res.planTaskAssetDto.length) return;
      res.planTaskAssetDto.forEach((item) => state.list.push(item));
      state.activePage += 1;
    })
    .catch(() => {
      state.loading = false;
    });
}

/**
 * @function 加载
 */
function onLoading() {
  if (state.finished) return;
  queryList(state.activePage);
}

/**
 * 关键字搜索回调
 */
function search() {
  refreshList();
}

/**
 * 列表刷新
 */
function refreshList() {
  state.activePage = 1;
  state.loading = true;
  state.finished = false;
  state.list = [];
  onLoading();
}

onMounted(() => {
  eventCenter.on(getCurrentInstance().router?.onShow as string, () => {
    refreshList();
  });
});
</script>
<template>
  <view class="inspection-detail app-page--1">
    <app-navbar :title="params.from ? TITLE_CONSTANT[params.from] : '巡检任务'" />
    <plan-task-head-card
      :placeholder="params.from ? CARD_TITLE_CONTENT[params.from] : '已巡检数量'"
    />
    <nut-searchbar
      v-model="filter.searchValue"
      @search="search"
      placeholder="输入设备编号、设备名称，查询任务"
      input-background="#EAEBED"
      class="inspection-detail__search"
    >
      <template v-slot:leftin>
        <nut-icon-search2 />
      </template>
      <template v-slot:rightout>
        <view class="inspection-detail__filter" @click="displayPopup">
          <app-nut-icon-horizontal-n />&nbsp;
          <text id="popId">筛选</text>
        </view>
        <nut-popover
          v-model:visible="filter.filterItemVisible"
          :list="filter.filterItemList"
          location="bottom-end"
          targetId="popId"
          @choose="filterItemChoose"
        />
      </template>
    </nut-searchbar>
    <nut-tabs
      v-model="state.activeStatus"
      @change="refreshList()"
      v-if="params.handleStatus === '2'"
    >
      <nut-tab-pane
        style="display: none !important"
        v-for="{ title, value } in state.statusQuantity"
        :key="value"
        :title="title"
        :pane-key="value"
      />
    </nut-tabs>
    <scroll-view
      class="app-page__wrapper"
      :scroll-y="true"
      :lower-threshold="100"
      @scrolltolower="onLoading()"
    >
      <view class="inspection-list__wrapper">
        <view
          class="inspection-item"
          v-for="item in state.list"
          :key="item.id || ''"
          @click="
            navigateTo({
              url: `/pages/inspection/edit/index?assetId=${item.assetId}&planTaskId=${
                item.planTaskId
              }${params.from ? '&from=' + params.from : ''}`,
            })
          "
        >
          <!--设备巡检-->
          <view v-if="params.planBizType === '1'">
            <view class="inspection-item__header">
              <view class="inspection-item__header--left">
                <text class="inspection-item__title">{{ item.assetName }}</text>
              </view>
              <view class="inspection-item__header--right" v-if="item.handleStatus == 1">
                <text
                  class="inspection-item__status"
                  :style="{
                    color: item.resultStatus ? PLAN_TASK_STATUS_COLOR[item.resultStatus] : '#999',
                    backgroundColor: item.resultStatus
                      ? PLAN_TASK_STATUS_BG_COLOR[item.resultStatus]
                      : '#999',
                  }"
                  >{{ item.resultStatus ? PLAN_TASK_STATUS[item.resultStatus] : '异常' }}</text
                ><text class="inspection-item__status__report" v-if="item.dealType === 1"
                  >已上报</text
                >
              </view>
            </view>
            <view>
              <text class="inspection-item__title">{{ item.assetCode || '_' }}</text>
            </view>
            <view>
              <text>资产分类:&nbsp;&nbsp;</text>
              <text>{{ item.assetTypeName || '_' }}</text>
            </view>
            <view>
              <text>所属区域:&nbsp;&nbsp;</text>
              <text>{{ item.areaName || '_' }}</text>
            </view>
          </view>
          <!-- 区域巡检-->
          <view v-else>
            <view class="inspection-item__header">
              <view class="inspection-item__header--left">
                <text class="inspection-item__title">{{ item.assetName || '-' }}</text>
              </view>
            </view>
            <view>
              <text>所属区域:&nbsp;&nbsp;</text>
              <text>{{ item.areaName || '_' }}</text>
            </view>
          </view>
        </view>
      </view>
      <view class="app-page__list-tips">
        <text v-if="!state.list.length">暂无数据！</text>
        <text v-else-if="state.list.length && state.loading">加载中...</text>
        <text v-else-if="state.list.length && state.finished">加载完成!</text>
      </view>
    </scroll-view>

    <app-region-list-selector-popup
      v-model="filter.appRegionListSelectorPopupIsShow"
      @on-selected="
        (value) => {
          filter.searchRegion = value;
          refreshList();
        }
      "
    />
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
